package com.anosine.gpsl.android.widget;

import java.lang.reflect.Field;

import com.anosine.gpsl.android.AppConstants;
import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.WebConstants;
import com.anosine.gpsl.android.entity.Login;
import com.anosine.gpsl.android.util.HttpRequestListener;
import com.anosine.gpsl.android.util.SendHttpUtils;
import com.anosine.gpsl.android.util.StringUtil;
import com.anosine.gpsl.android.util.ToastHelper;
import com.anosine.gpsl.android.util.UserInfoProxy;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
 * @Title: FloatWindowSmallView
 * @Package com.anosine.gpsl.android.widget
 * @Description: 
 * @author: sunny
 * @date: 2015-11-23
 * @version V1.0
 */
public class FloatWindowSmallView extends LinearLayout {

	/**
	 * 记录小悬浮窗的宽度
	 */
	public static int windowViewWidth;

	/**
	 * 记录小悬浮窗的高度
	 */
	public static int windowViewHeight;

	/**
	 * 记录系统状态栏的高度
	 */
	private static int statusBarHeight;

	/**
	 * 用于更新小悬浮窗的位置
	 */
	private WindowManager windowManager;

	/**
	 * 小悬浮窗的布局
	 */
	private LinearLayout smallWindowLayout;

	/**
	 * 小悬浮窗的参数
	 */
	private WindowManager.LayoutParams mParams;

	/**
	 * 记录当前手指位置在屏幕上的横坐标值
	 */
	private float xInScreen;

	/**
	 * 记录当前手指位置在屏幕上的纵坐标值
	 */
	private float yInScreen;

	/**
	 * 记录手指按下时在屏幕上的横坐标的值
	 */
	private float xDownInScreen;

	/**
	 * 记录手指按下时在屏幕上的纵坐标的值
	 */
	private float yDownInScreen;

	/**
	 * 记录手指按下时在小悬浮窗的View上的横坐标的值
	 */
	private float xInView;

	/**
	 * 记录手指按下时在小悬浮窗的View上的纵坐标的值
	 */
	private float yInView;

	
	/**
	 * 记录小火箭的高度
	 */
	private boolean  isShow = true;
	/**
	 * 设置布局
	 */
	private RelativeLayout allwindow;
	private LinearLayout setting;
	private ImageView set_Ok, set_No,centeriv;
	TextView rocket_img;
	Context conText;
	@SuppressLint("ResourceAsColor")
	public FloatWindowSmallView(final Context context) {
		super(context);
		conText=context;
		windowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		LayoutInflater.from(context).inflate(R.layout.float_window_small, this);
		smallWindowLayout = (LinearLayout) findViewById(R.id.small_window_layout);
		allwindow= (RelativeLayout) findViewById(R.id.allwindow);
		////////////////////////////////////////////////////
		setting = (LinearLayout) findViewById(R.id.setting);
		set_Ok = (ImageView) findViewById(R.id.set_Ok);
		set_No = (ImageView) findViewById(R.id.set_No);
		centeriv=(ImageView) findViewById(R.id.centeriv);
		////////////////////////////////////////////////
		windowViewWidth = allwindow.getLayoutParams().width;
		windowViewHeight = allwindow.getLayoutParams().height;

		Login info = UserInfoProxy.getInstance().getLoginInfo();
		if (info != null) {
			if("0".equals(info.safe)){
				set_No.setImageResource(R.drawable.nofortify_press);
				set_Ok.setImageResource(R.drawable.fortify_normal);
				centeriv.setImageResource(R.drawable.center_nofortify);
			}else{
				set_No.setImageResource(R.drawable.nofortify_normal);
				set_Ok.setImageResource(R.drawable.fortify_press);
				centeriv.setImageResource(R.drawable.center_fortify);
				
			}
		}
		set_Ok.setOnClickListener(new OnClickListener() {

			@SuppressLint("ResourceAsColor")
			@Override
			public void onClick(View v) {
				set_Ok.setImageResource(R.drawable.fortify_press);
				set_No.setImageResource(R.drawable.nofortify_normal);
				centeriv.setImageResource(R.drawable.center_fortify);
				clickBtnSheFang("1");
			}
		});
		set_No.setOnClickListener(new OnClickListener() {

			@SuppressLint("ResourceAsColor")
			@Override
			public void onClick(View v) {
				set_No.setImageResource(R.drawable.nofortify_press);
				set_Ok.setImageResource(R.drawable.fortify_normal);
				centeriv.setImageResource(R.drawable.center_nofortify);
				clickBtnSheFang("0");
			}
		});
	}

	/**
	 * 方法名：clickBtnSheFang() 功 能：点击设防按钮后进行的操作 参 数：无 返回值：无 　　　
	 */
	private void clickBtnSheFang(final String info) {
		// 0:未设防；1：已设防
		final Login userInfo = UserInfoProxy.getInstance()
				.getLoginInfo();
		String url = String.format("%1s/%2s", AppConstants.sCommonUrl,
				WebConstants.Do_SaveObjectSetSafe_Action);
		RequestParams params = new RequestParams();

		params.addBodyParameter("objectinfo.is_set_safe", info);
		params.addBodyParameter("objectinfo.objectid", userInfo.objectid);
		params.addBodyParameter("usermd5", userInfo.userMd5);
		SendHttpUtils sendHttp = new SendHttpUtils();
		TypeToken type = new TypeToken<String>() {
		};
		/**
		 * 方法名：(String url, RequestParams params, final TypeToken<T> type, final
		 * HttpRequestListener listener) 功 能：重写的SendHttpUtils类的doRequest方法 参 数：
		 * url　服务器地址　params 传给服务器的参数，值　 HttpRequestListener
		 * listener　HttpRequestListener接口 返回值：无
		 * */
		sendHttp.doRequest(url, params, type,
				new HttpRequestListener<String>() {
					/**
					 * 方法名：onSuccess(String result, String t) 功 能：解析json成功 参
					 * 数：String result, String t 返回值：无
					 */
					@Override
					public void onSuccess(String result, String t) {
						if (StringUtil.isNotEmpty(result)
								&& result.contains("form_save_success")) {
							userInfo.safe = info;
							UserInfoProxy.getInstance().setLoginUserInfo(
									userInfo);
							//发送广播
							Intent i = new Intent();
							i.setAction("ChangeFortifiedState");
							conText.sendBroadcast(i);
							
						}
					}

					/**
					 * 方法名：onFailure(String error) 功 能：json解析错误后执行的方法 参
					 * 数：error　解析返回的错误信息 返回值：无
					 */
					@Override
					public void onFailure(String error) {
						ToastHelper.toast(error);
					}
				});
	}

	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			MyWindowManager.isShowSetWindow = true;

			//发一个广播
			Intent i1 = new Intent();
			i1.setAction("OperateTrue");
			conText.sendBroadcast(i1);
			
			// 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
			xInView = event.getX();
			yInView = event.getY();
			xDownInScreen = event.getRawX();
			yDownInScreen = event.getRawY() - getStatusBarHeight();
			xInScreen = event.getRawX();
			yInScreen = event.getRawY() - getStatusBarHeight();
			
			break;
		case MotionEvent.ACTION_MOVE:
			MyWindowManager.isShowSetWindow = true;

			//发一个广播
			Intent i2 = new Intent();
			i2.setAction("OperateTrue");
			conText.sendBroadcast(i2);
			
			xInScreen = event.getRawX();
			yInScreen = event.getRawY() - getStatusBarHeight();
			// 手指移动的时候更新小悬浮窗的状态和位置
			updateViewStatus();
			updateViewPosition();
			
			
			break;
		case MotionEvent.ACTION_UP:
			MyWindowManager.isShowSetWindow = false;
			//发一个广播
			Intent i3 = new Intent();
			i3.setAction("OperateTrue");
			conText.sendBroadcast(i3);
			
			updateViewStatus();
			// 如果手指离开屏幕时，xDownInScreen和xInScreen相等，且yDownInScreen和yInScreen相等，则视为触发了单击事件。
			if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {

								MyWindowManager.isFirst=false;
								if (isShow) {
									isShow = false;
									setting.setVisibility(View.VISIBLE);
									MyWindowManager.isShowSetWindow = true;
									//发一个广播
									Intent i = new Intent();
									i.setAction("OperateFalse");//OperateTrue 出来钥匙不消失
									conText.sendBroadcast(i);
								} else {
									isShow = true;
									setting.setVisibility(View.GONE);
									//MyWindowManager.isShowSetWindow = true;
									//发一个广播
									Intent i = new Intent();
									i.setAction("OperateFalse");
									conText.sendBroadcast(i);
								}
				
							
					
			}
			break;
		default:
			break;
		}
		return false; 
	}

	/**
	 * 将小悬浮窗的参数传入，用于更新小悬浮窗的位置。
	 * 
	 * @param params
	 *            小悬浮窗的参数
	 */
	public void setParams(WindowManager.LayoutParams params) {
		mParams = params;
	}

	/**
	 * 更新小悬浮窗在屏幕中的位置。
	 */
	private void updateViewPosition() {
		mParams.x = (int) (xInScreen - xInView);
		mParams.y = (int) (yInScreen - yInView);
		windowManager.updateViewLayout(this, mParams);
		// MyWindowManager.updateLauncher();
	}

	/**
	 * 更新View的显示状态，判断是显示悬浮窗还是小火箭。
	 */
	private void updateViewStatus() {
		
		mParams.width = windowViewWidth;
		mParams.height = windowViewHeight;
		windowManager.updateViewLayout(this, mParams);
		smallWindowLayout.setVisibility(View.VISIBLE);
		
	}

	/**
	 * 用于获取状态栏的高度。
	 * 
	 * @return 返回状态栏高度的像素值。
	 */
	private int getStatusBarHeight() {
		if (statusBarHeight == 0) {
			try {
				Class<?> c = Class.forName("com.android.internal.R$dimen");
				Object o = c.newInstance();
				Field field = c.getField("status_bar_height");
				int x = (Integer) field.get(o);
				statusBarHeight = getResources().getDimensionPixelSize(x);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return statusBarHeight;
	}

}
